import time
import logging
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

logger = logging.getLogger(__name__)


class BilibiliVideoPage:
    def __init__(self, driver):
        self.driver = driver
        # 核心选择器（基于实际元素）
        self.base_selector = "video-like.video-toolbar-left-item"
        self.like_selector = f".{self.base_selector}"
        self.liked_selector = f".{self.base_selector}.on"

    def like_video(self):
        """简化版点赞逻辑：定位→操作→验证"""
        logger.info("执行点赞操作")
        try:
            # 等待视频加载并滚动到按钮区域
            WebDriverWait(self.driver, 4).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".bpx-player-video-wrap"))
            )
            self.driver.execute_script("window.scrollTo(0, 600);")
            time.sleep(2)

            # 检查是否已点赞
            if self._is_liked():
                logger.info("已点赞，无需操作")
                return True

            # 定位并点击点赞按钮
            like_btn = WebDriverWait(self.driver, 4).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, self.like_selector))
            )
            try:
                like_btn.click()
            except:
                self.driver.execute_script("arguments[0].click();", like_btn)

            # 等待并验证结果
            time.sleep(3)
            if self._is_liked():
                logger.info("点赞成功")
                return True
            logger.error("点赞失败：未检测到点赞状态")
            return False

        except Exception as e:
            logger.error(f"点赞流程异常: {str(e)}")
            return False

    def _is_liked(self):
        """内部辅助方法：判断是否已点赞"""
        try:
            # 优先检查已点赞选择器
            self.driver.find_element(By.CSS_SELECTOR, self.liked_selector)
            return True
        except:
            # 备选检查按钮class
            try:
                return "on" in self.driver.find_element(
                    By.CSS_SELECTOR, self.like_selector
                ).get_attribute("class")
            except:
                return False

    def is_video_liked(self):
        """外部调用的点赞状态检查（复用内部方法）"""
        return self._is_liked()